#include "jitter_storage_filter.h"

#include <muduo/net/EventLoop.h>

namespace fusion_perception {

JitterStorageFilter::JitterStorageFilter(size_t count)
    : count_(count)
{
    timerId_ = eventLoopThread_.startLoop()->runEvery(60.0, std::bind(&JitterStorageFilter::onTimeout, this));
}

JitterStorageFilter::~JitterStorageFilter(void)
{
    eventLoopThread_.startLoop()->cancel(timerId_);
}

bool JitterStorageFilter::filtering(int64_t id)
{
    std::lock_guard<std::mutex> locker(mutexLock_);

    filterUMap_[id].latestMicroTs = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock().now().time_since_epoch()).count();

    if (filterUMap_[id].count++ <= count_ - 1) {
        return false;
    } else {
        return true;
    }
}

void JitterStorageFilter::onTimeout(void)
{
    std::lock_guard<std::mutex> locker(mutexLock_);

    for (auto begin = filterUMap_.begin(); begin != filterUMap_.end();) {
        if (std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock().now().time_since_epoch()).count() - begin->second.latestMicroTs > int64_t(5) * 60 * 1000000) {
            begin = filterUMap_.erase(begin);
        } else {
            ++begin;
        }
    }
}

}